﻿using DncLite.Application.Interfaces;
using DncLite.Application.ViewModels.Student;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;

namespace DncLite.UI.Web.Pages.Student
{
    public class CreateModel : PageModel
    {
        private readonly IStudentAppService _studentAppService;
        private readonly IMemoryCache _cache;
        public CreateModel(
            IStudentAppService studentAppService
            , IMemoryCache cache)
        {
            _cache = cache;
            _studentAppService = studentAppService;
        }

        [BindProperty]
        public StudentViewModel StudentViewModel { get; set; }

        public string ErrorMessage { get; set; }

        public IActionResult OnGet()
        {
            try
            {
                _cache.Remove("ErrorData");
                //ViewBag.ErrorData = null;
                // 视图模型验证
                if (!ModelState.IsValid)
                    return Page();
                StudentViewModel = new StudentViewModel
                {
                    BirthDate = DateTime.Now.AddYears(-20),
                    City = "ChonqQing",
                    County = "",
                    Email = "rector@gmail.com",
                    Name = "Rector",
                    Phone = "13100000000",
                    Province="ChongQing",
                    Street="YuBei"
                };
                // 执行添加方法
                _studentAppService.Register(StudentViewModel);

                var errorData = _cache.Get("ErrorData");
                if (errorData == null)
                {
                    ErrorMessage = "Student Registered!";
                }
                else
                {
                    ErrorMessage = string.Join(",", (List<string>)errorData);
                }
                return Page();
            }
            catch (Exception e)
            {
                ErrorMessage = e.ToString();
                return Page();
            }
        }
    }
}